package web.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yc.bean.User;
import com.yc.biz.UserBiz;
import com.yc.biz.impl.UserBizImpl;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
	UserBiz ub = new UserBizImpl();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String op=req.getParameter("op");
		PrintWriter out=resp.getWriter();
		
		if( "login".equals(op) ){
			login(req,resp,out);
		}else if( "reg".equals(op) ){
			reg(req,resp,out);
		}else if( "logout".equals(op) ){
			logout(req,resp,out);
		}
	}

	//退出登录
	private void logout(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
		req.getSession().removeAttribute("user");
		out.print(0);
	}

	//注册
	private void reg(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
		//先得到用户名和密码
		String rnickname=req.getParameter("rnickname");
		String rpwd=req.getParameter("rpwd");
		
		int result = ub.reg(rnickname, rpwd);
		out.print(result);
	}

	//登录
	private void login(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
	//先得到用户名和密码
		String nickname=req.getParameter("nickname");
		String pwd=req.getParameter("pwd");
		
		User user=ub.login(nickname, pwd);
		if( user == null ){
			//登陆失败
			out.print(0);
		}else if(user.getStatus() != 2){
			//登陆成功
			req.getSession().setAttribute("user", user);
			//存session
			req.getSession().setAttribute("uname", user.getNickname());
			req.getSession().setAttribute("mno", user.getMno());
			out.print(1);
		}else{
			out.print(2);
		}
		
	}
	
}
